import Link from 'next/link'
import Select from '@c/select'
import { getVodCollectionLines } from '@/api/vod'
import { useEffect, useState } from 'react'
import styles from './index.module.scss'
import cm from 'classnames'
import LiveLoading from '@c/live-icon'
import SortSvg from '@c/svg/sort'
import { cacheLineState, userInfo } from '@/store'
import { useRecoilState, useRecoilValue } from 'recoil'
import { useRouter } from 'next/router'
import Loading from '@c/request-loading'

const Index = props => {
  const { selectionInfo, currPlayLines, setErrorCode, isShows, isMovie } = props
  const user = useRecoilValue(userInfo)
  const {
    query: { id: cid, ep }
  } = useRouter()
  const [lineState, updateLineState] = useRecoilState(cacheLineState)
  const [openLinePanel, toggleLinePanel] = useState(false)
  const [currLineGroup, updateLineGroup] = useState(null)
  const [playParams, setPlayParams] = useState({
    page: 1,
    sort: 1
  })

  const updateCurrLine = (item, index) => {
    let code = 0
    if (item.isOfficial) {
      if (typeof user?.token !== 'undefined' && !user?.token) {
        code = '7'
      } else if (!user.isVip) {
        code = '1-1'
      }
    }
    setErrorCode(code)
    updateLineState({
      ...item,
      index
    })
  }

  // 更新剧集
  const updateLines = page => {
    setPlayParams({
      ...playParams,
      page
    })
  }

  useEffect(() => {
    const { sort, page } = playParams
    getVodCollectionLines({ cid, page, pageSize: selectionInfo.pageSize, sort }).then(res => {
      updateLineGroup(res.data)
    })
  }, [playParams.page])

  const stop = e => {
    e.stopPropagation()
  }

  const updateSort = () => {
    setPlayParams({
      ...playParams,
      sort: playParams.sort === 1 ? 2 : 1
    })
    const newData = {
      ...currLineGroup
    }
    newData.eporder = [...newData.eporder].reverse()
    updateLineGroup(newData)
  }

  return (
    <div className={styles.playFull}>
      <div className={styles.lines}>
        {!isMovie &&
          (currPlayLines.length ? (
            currPlayLines?.slice(0, 2).map((item, index) => {
              return (
                <div
                  key={index}
                  className={cm({
                    [styles.lineBtn]: true,
                    [styles.lineLive]: !item.isOfficial && (lineState.lId === item.lId || lineState.index == index),
                    [styles.lineOfficial]: item.isOfficial,
                    [styles.lineThird]: !item.isOfficial
                  })}
                  onClick={() => updateCurrLine(item, index)}
                >
                  {(lineState.lId === item.lId || lineState.index == index) && (
                    <LiveLoading type={item.isOfficial ? 'vod' : 'default'} style={{ marginLeft: 0 }} />
                  )}
                  <span>{item.name}</span>
                  {item.isOfficial && (
                    <div className={styles.vipTip}>
                      <span>{user.token ? '超清流畅无广告' : '登录领会员畅享'}</span>
                    </div>
                  )}
                </div>
              )
            })
          ) : (
            <div className={styles.noLine}>暂无可播放线路～</div>
          ))}
        {currPlayLines.length > 1 && !isMovie && (
          <div
            className={cm(styles.lineBtn, styles.lineThird, styles.switchLine, openLinePanel ? styles.openPanel : '')}
            onClick={e => [stop(e), toggleLinePanel(!openLinePanel)]}
          >
            <img src="/images/arrow.webp" className={styles.arrow} alt="箭头" />
          </div>
        )}

        {(openLinePanel || isMovie) && (
          <div className={styles.linePanel}>
            {currPlayLines.length > 2 || isMovie ? (
              currPlayLines.map((item, index) => {
                return (
                  <div
                    key={index}
                    className={cm({
                      [styles.lineBtn]: true,
                      [styles.lineLive]: !item.isOfficial && (lineState.lId === item.lId || lineState.index == index),
                      [styles.lineOfficial]: item.isOfficial,
                      [styles.lineThird]: !item.isOfficial,
                      [styles.linePanelItem]: true
                    })}
                    onClick={() => updateCurrLine(item, index)}
                  >
                    <span>{item.name}</span>
                    {(lineState.lId === item.lId || lineState.index == index) && (
                      <LiveLoading type={item.isOfficial ? 'vod' : 'default'} />
                    )}
                  </div>
                )
              })
            ) : (
              <div className={styles.nullLine}>
                <img src="/images/null.png" alt="无数据" className={styles.img} />
                <p className={styles.text}>暂无更多播放线路~</p>
              </div>
            )}
          </div>
        )}
      </div>
      {!selectionInfo.noSelections && (
        <div className={styles.orderBox}>
          <span className={styles.jujiText}>剧集</span>
          <Select
            width={168}
            className={styles.selectSpace}
            currentValue={selectionInfo.pageNo}
            list={selectionInfo.selectionGroup}
            onChange={updateLines}
          />
          <SortSvg width={40} sort={playParams.sort} onClick={e => [stop(e), updateSort()]} />
        </div>
      )}
      {!isMovie && Array.isArray(currLineGroup?.eporder) && (
        <div className={styles.jujiBox}>
          {currLineGroup ? (
            currLineGroup.eporder?.map((item, index) => {
              return (
                <Link
                  href={`/vod/play-official/${cid}/${item.eporder}`}
                  replace
                  key={index}
                  className={cm(styles.jujiItem, {
                    [styles.jujiActive]: item.eporder == ep,
                    [styles.jujiShow]: isShows,
                    textEllipsis: isShows
                  })}
                >
                  {isShows ? item.videoName || item.eporder : item.eporder}
                </Link>
              )
            })
          ) : (
            <Loading />
          )}
        </div>
      )}
    </div>
  )
}

export default Index
